package com.yunzheng.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunzheng.dto.FileChangeDTO;
import com.yunzheng.dto.FilePostDTO;
import com.yunzheng.vo.FileShowContentVO;
import com.yunzheng.vo.FileShowVO;
import com.yunzheng.entity.ProjectFile;
import com.yunzheng.entity.ProjectFileContent;
import com.yunzheng.exception.ServiceException;
import com.yunzheng.mapper.ProjectFileContentMapper;
import com.yunzheng.util.MdToHtml;
import com.yunzheng.util.SnowFlakeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzheng.mapper.ProjectFileMapper;
import com.yunzheng.service.ProjectFileService;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 郭思良
 * @create 2020-07-23 15:38
 */

@Service
public class ProjectFileServiceImpl extends ServiceImpl<ProjectFileMapper, ProjectFile> implements ProjectFileService {

    @Resource
    private ProjectFileMapper projectFileMapper;

    @Resource
    private ProjectFileContentMapper projectFileContentMapper;

    @Override
    public void filePost(String userId, FilePostDTO filePostDTO) {
        ProjectFile file = new ProjectFile(SnowFlakeUtil.nextId(), filePostDTO.getFileTitle(), filePostDTO.getProjectId(), userId, LocalDateTime.now());
        ProjectFileContent fileContent = new ProjectFileContent(file.getFileId(), filePostDTO.getFileContent(), MdToHtml.convert(filePostDTO.getFileContent()), LocalDateTime.now(),LocalDateTime.now());
        projectFileMapper.insert(file);
        projectFileContentMapper.insert(fileContent);
        log.debug("成功上传文档：" + file.getFileTitle());
    }

    @Override
    public List<FileShowVO> getFileListById(String projectId) {
        return projectFileMapper.selectFiles(projectId);
    }

    @Override
    public FileShowContentVO getFileById(String fileId) {
        return projectFileMapper.selectFileById(fileId);
    }

    @Override
    public void changeFile(FileChangeDTO fileChangeDTO) {
        ProjectFile file = new ProjectFile();
        file.setFileId(fileChangeDTO.getFileId()).setFileTitle(fileChangeDTO.getFileTitle());
        ProjectFileContent fileContent = new ProjectFileContent();
        fileContent.setFileId(fileChangeDTO.getFileId()).setFileContent(fileChangeDTO.getFileContent()).setFileContentHtml(MdToHtml.convert(fileChangeDTO.getFileContent()));
        projectFileMapper.updateById(file);
        projectFileContentMapper.updateById(fileContent);
    }

    @Override
    public void removeFile(String fileId) {
        if (fileId == null) {
            throw new ServiceException("传输数据出错");
        } else {
            projectFileMapper.deleteById(fileId);
            projectFileContentMapper.deleteById(fileId);
        }
    }

}

